/* $Id: Misc.java 133 2011-08-26 12:01:00Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.utils;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class Misc
{
	@SuppressWarnings({ "rawtypes" })
	public static Map remap(HttpServletRequest request)
	{
		HashMap<String, String> res = new HashMap<String, String>();
		Enumeration en = request.getParameterNames();
		while (en.hasMoreElements())
		{
			String key = en.nextElement().toString();
			res.put(key, request.getParameter(key));
		}
		return res;
	}
	
	@SuppressWarnings("unchecked")
	public static String attachPager(HttpServletRequest req)
	{
		StringBuilder sb = new StringBuilder();
		sb.append("<div class='pager'>");
		Integer currPage = Parsers.parseInteger(req.getParameter("page"));
		String url = req.getRequestURL().toString();
		int c = 0;
		Enumeration<Object> params = req.getParameterNames();
		while (params.hasMoreElements())
		{
			if (c++ > 0)
				url += "&";
			else
				url += "?";
			String key = params.nextElement().toString();
			url += key + "=" + req.getParameter(key);
		}
		String urlPrev = "";
		String urlNext = "";
		if (url.indexOf("page=" + currPage) >= 0)
		{
			urlPrev = url.replace("page=" + currPage, "page=" + (currPage-1));
			urlNext = url.replace("page=" + currPage, "page=" + (currPage+1));
		}
		else
		{
			urlPrev = url + (url.indexOf('?') >= 0 ? "&" : "?") + "page=" + (currPage-1);
			urlNext = url + (url.indexOf('?') >= 0 ? "&" : "?") + "page=" + (currPage+1);
		}
		sb.append("<table width='50%' align='center'><tr>");
		sb.append("<td><a href=\"" + urlPrev + "\">Prev</a></td>");
		sb.append("<td align='right'><a href=\"" + urlNext + "\">Next</a></td>");
		sb.append("</tr></table>");
		sb.append("</div>");
		return sb.toString();
	}
}
